package com.jn.erp.wechat.staff.api.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jn.erp.common.constant.UserConstants;
import com.jn.erp.common.core.result.AjaxResult;
import com.jn.erp.common.core.text.Convert;
import com.jn.erp.common.exception.ServiceException;
import com.jn.erp.common.exception.user.UserNotExistsException;
import com.jn.erp.common.exception.user.UserPasswordNotMatchException;
import com.jn.erp.common.utils.StringUtils;
import com.jn.erp.security.context.AuthenticationContextHolder;
import com.jn.erp.security.entity.*;
import com.jn.erp.security.service.SysPermissionService;
import com.jn.erp.security.service.TokenService;
import com.jn.erp.security.sysservice.SysRoleService;
import com.jn.erp.security.sysservice.SysUserRoleService;
import com.jn.erp.security.utils.SecurityUtils;
import com.jn.erp.web.api.sys.entity.SysOrg;
import com.jn.erp.web.api.sys.service.SysOrgUserService;
import com.jn.erp.wechat.common.api.entity.WxMenu;
import com.jn.erp.wechat.common.api.service.WxMenuService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 *  教师端 登录
 * </pre>
 *
 * @author sunjiyong
 * @since 2024/10/24 14:17
 */
@AllArgsConstructor
@RestController
@RequestMapping("/wx/staff")
public class MpLoginController {

    @Autowired
    private TokenService tokenService;

    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private SysOrgUserService sysOrgUserService;

    @Autowired
    private com.jn.erp.security.sysservice.SysPermissionService permissionService;

    @Autowired
    private WxMenuService wxMenuService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleService roleService;

    /**
     * 移动端验证码登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/mobileLogin")
    public AjaxResult mobileLogin(@RequestBody LoginBody loginBody) {
        JSONObject ajax=new JSONObject();
        String password = loginBody.getPassword();
        String username = loginBody.getUsername();
        // 登录前置校验
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password))
        {
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new UserPasswordNotMatchException();
        }
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username+"#0", password);
            AuthenticationContextHolder.setContext(authenticationToken);
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new UserPasswordNotMatchException();
            } else {
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        // 生成令牌
        String token = tokenService.createToken(loginUser);

        ajax.put("token", token);
        Long userId = loginUser.getUserId();
        if (userId != null) {
            List<SysOrg> orgs = sysOrgUserService.getOrgListByUserId(userId);
            ajax.put("orgs", orgs);
        }
        return AjaxResult.success(ajax);
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo(LoginBody loginBody) {
        JSONObject ajax=new JSONObject();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        ajax.put("user", user);
        //当前用户所在机构
        String orgId=loginBody.getOrgId();

        List<SysUserRole> userRoles = sysUserRoleService.getRolesByUserOrgId(user.getId(), Long.valueOf(orgId));
        if(userRoles.size()>0){
            List<Long> roleIds = userRoles.stream().map(r -> r.getRoleId()).collect(Collectors.toList());
            // 角色集合
            QueryWrapper<SysRole> qr=new QueryWrapper<>();
            qr.in("role_id",roleIds);
            List<SysRole> perms = roleService.list(qr);
            Set<String> roles = new HashSet<String>();
            for (SysRole perm : perms) {
                if (StringUtils.isNotNull(perm)) {
                    roles.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
                }
            }
            ajax.put("roles", roles);

            // 权限集合
            Set<String> permissions = new HashSet<String>();
            // 多角色设置permissions属性，以便数据权限匹配权限
            for (SysUserRole role : userRoles) {
                Set<String> rolePerms = permissionService.selectMenuPermsByRoleId(role.getRoleId());
                permissions.addAll(rolePerms);
            }
            ajax.put("permissions", permissions);

            //导航页签
            String idStr = roleIds.stream().map(id -> Convert.toStr(id)).collect(Collectors.joining(","));
            List<WxMenu> wxMenus =wxMenuService.wxBarMenus(idStr);
            ajax.put("list", wxMenus);
        }
        return AjaxResult.success(ajax);
    }

}
